package org.bing.engine.console.message;

import org.bing.engine.common.message.HandlerAdapter;
import org.bing.engine.common.message.Message;
import org.bing.engine.console.service.ContainerInstanceManager;
import org.bing.engine.console.service.ControllerManager;
import org.bing.engine.core.domain.ContainerInstance;
import org.bing.engine.core.domain.Controller;

public class ContainerBeatHandler extends HandlerAdapter {
    private ContainerInstanceManager containerInstanceManager;
    private ControllerManager controllerManager;

    public void setControllerManager(ControllerManager manager) {
        this.controllerManager = manager;
    }

    public void setContainerInstanceManager(ContainerInstanceManager manager) {
        this.containerInstanceManager = manager;
    }

    @Override
    protected Object doHandle(Message msg) {
        Object body = msg.getBody();
        if (body == null || !body.getClass().equals(ContainerInstance.class)) {
            return null;
        }
        ContainerInstance instance = (ContainerInstance) body;
        ContainerInstance instance2 = containerInstanceManager.findByGlobalId(instance.getGlobalId());
        if (instance2 != null) {
            copy(instance, instance2);
            if (instance.getController() != null) {
                Controller controller = controllerManager.findByGlobalId(instance.getController().getGlobalId());
                instance2.setController(controller);
            }
        } else {
            logger.info("Add new container instance to console " + instance);
            instance2 = instance;
        }
        containerInstanceManager.save(instance2);
        return instance2;
    }

    private void copy(ContainerInstance src, ContainerInstance dest) {
        // TODO impl copy other property
        dest.setController(src.getController());
        dest.setLastActivityTime(src.getLastActivityTime());
    }
}
